package org.kd.ssh.web.action;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.kd.ssh.domain.Goods;
import org.kd.ssh.domain.UserInfo;
import org.kd.ssh.service.GoodsService;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

public class GoodsAction extends ActionSupport implements ModelDriven<Goods>{
	private Goods goods = new Goods();
	private List<Goods> goodses;
	
	private String term;
	
	private GoodsService goodsService;
	
	public void setGoodsService(GoodsService goodsService) {
		this.goodsService = goodsService;
	}

	public List<Goods> getGoodses() {
		return goodses;
	}

	public void setGoodses(List<Goods> goodses) {
		this.goodses = goodses;
	}
	
	public String getTerm() {
		return term;
	}

	public void setTerm(String term) {
		this.term = term;
	}

	@Override
	public Goods getModel() {
		// TODO Auto-generated method stub
		return this.goods;
	}
	
	
	public String findByNM(){
		goods = goodsService.findByNM(goods.getNm());
		return "findByNMSuccess";
	}
	
	public String save(){
		UserInfo existUser = (UserInfo) ServletActionContext.getRequest().getSession().getAttribute("loginUser");
		goodsService.save(goods,existUser);
		return "saveSuccess";
	}
	
	public String findByNameLike(){
		goodses = goodsService.findByNameLike(term);
		return "findByNameLikeSuccess";
	}
	
	public String findByGoodsName(){
		goods = goodsService.findByGoodsName(goods.getName());
		return "findByGoodsNameSuccess";
	}
	
	public String out(){
		try{
			UserInfo existUser = (UserInfo) ServletActionContext.getRequest().getSession().getAttribute("loginUser");
			goodsService.out(goods,existUser);
		}catch (Exception e) {
			this.addActionError(e.getMessage());
			return "outFail";
		}
		
		return "outSuccess";
	}
	
	public String query(){
		DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Goods.class);
		if(StringUtils.isNotBlank(goods.getNm())){
			detachedCriteria.add(Restrictions.eq("nm", goods.getNm()));
		}
		if(StringUtils.isNotBlank(goods.getName())){
			detachedCriteria.add(Restrictions.like("name", "%"+goods.getName()+"%"));
		}
		if(goods.getStore() != null && goods.getStore().getId().trim().length() > 0){
			detachedCriteria.add(Restrictions.eq("store", goods.getStore()));
		}
		goodses = goodsService.findByConditions(detachedCriteria);
		return "querySuccess";
	}
	
}
